package com.hunter.api.http;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;

import com.auth0.jwt.JWT;
import com.hunter.api.bean.EntityBean;
import com.hunter.api.bean.SqlConfigBean;
import com.hunter.api.bean.UserBean;
import com.hunter.api.handler.EntityHandler;
import com.hunter.api.handler.SqlHandler;
import com.hunter.api.handler.UserHandler;
import com.hunter.api.handler.annotation.UserLoginToken;
import com.hunter.api.help.result.ErrorHelp;
import com.hunter.api.mapper.SqlMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author HunterHuang
 * @version 1.0
 * @ClassName UserHttp
 * @date 2019/5/30 14:44
 */
@Controller
@Slf4j
@CrossOrigin(origins = "*",maxAge = 3600)
@Transactional(propagation = Propagation.REQUIRED)

public class UserHttp {

    @Autowired
    private UserHandler userHandler ;
    @Autowired
    private EntityHandler entityHandler;
    @Autowired
    private SqlHandler sqlHandler;
    @Autowired
    private SqlMapper sqlMapper;


    @ResponseBody
    @RequestMapping("user/login")
    public JSONObject UserLogin(@RequestBody UserBean user){
        JSONObject json = new JSONObject();
        json = userHandler.Login(user);
        return json;
    }

    @UserLoginToken
    @ResponseBody
    @RequestMapping("user/info")
    public JSONObject UserInfo(HttpServletRequest httpServletRequest,UserBean user){
        JSONObject json = new JSONObject();


        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        Long userId = Long.valueOf(JWT.decode(token).getAudience().get(0));
        if (userId!=null) {
            log.info("进入用户查询");
            json = userHandler.UserInfo(userId);
        }else{
            json = ErrorHelp.TOKEN_ERROR;
        }
        return json;
    }

    /**
     * 发送验证码
     * @param mobileJson
     * @return
     */
    @ResponseBody
    @RequestMapping("user/sendVcode")
    public JSONObject sendVcode(@RequestBody JSONObject mobileJson ){
        JSONObject json = new JSONObject();
        try {
            // todo redis 限流 暂缓
            String vcode = ((int)((Math.random() * 9 + 1) * 100000)) + "";
            String mobile = mobileJson.getString("mobile");
            //todo 接入短信
            //json = ztyHelp.send(mobile,vcode);
            String code = json.getString("code");
            if ("20000".equals(code)) {
                EntityBean entity = new EntityBean();
                JSONObject data = new JSONObject();
                Long validity_time = System.currentTimeMillis() / 1000;
                data.put("vcode", vcode);
                data.put("validity_time", validity_time + 300);
                data.put("mobile", mobile);
                data.put("enabled", 1);
                entity.setData(data);
                entity.setCode("vcode");
                json = entityHandler.Entity(entity, "insert");
            }
        }catch (Exception e){
            e.printStackTrace();
            json.put("code", 500);
            json.put("msg", e.toString());
            json.put("data","{}" );
            return json;
        }
        return json;
    }


    /**
     * 检查验证码
     * @param vcodeJson
     * @return
     */
    @ResponseBody
    @RequestMapping("user/checkVcode")
    public JSONObject checkVcode(@RequestBody JSONObject vcodeJson ){
        JSONObject json = new JSONObject();
        try {
            String vcode= vcodeJson.getString("vcode");
            String mobile = vcodeJson.getString("mobile");
            SqlConfigBean sqlConfigBean = new SqlConfigBean();
            sqlConfigBean.setCode("vcode");
            sqlConfigBean = sqlMapper.SqlConfigInfo(sqlConfigBean);
            JSONObject data = new JSONObject();
            Long validity_time = System.currentTimeMillis()/1000;
            data.put("vcode",vcode);
            data.put("validity_time",validity_time);
            data.put("mobile",mobile);
            data.put("enabled",1);
            if (sqlConfigBean != null) {
                JSONObject config_json = JSONObject.parseObject(sqlConfigBean.getConfig_json());
                JSONObject futQuery = sqlHandler.queryScalar(config_json,data);
                json.put("code", 20000);
                json.put("msg", "查询成功");
                json.put("data", futQuery);
            } else {
                json = ErrorHelp.SQL_NOT_EXISTS;
            }
        }catch (Exception e){
            json.put("code", 500);
            json.put("msg", e.getMessage());
            json.put("data","{}" );
        }finally {
            return json;
        }
    }








}
